package com.github.permissiondog.cancanpbackend;

import com.github.permissiondog.cancanpbackend.dao.*;
import com.github.permissiondog.cancanpbackend.model.Role;
import com.github.permissiondog.cancanpbackend.model.TableQuestion;
import com.github.permissiondog.cancanpbackend.model.User;
import com.github.permissiondog.cancanpbackend.service.UserService;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.*;
import javax.servlet.annotation.*;

@WebListener
public class ContextListener implements ServletContextListener {

    public ContextListener() {
    }

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        initDatabase();
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
    }

    private void initDatabase() {
        try (SqlSession session = Database.getInstance().openSession()) {
            var userDao = session.getMapper(UserDao.class);
            userDao.createTable();
            var tableTemplateDao = session.getMapper(TableTemplateDao.class);
            tableTemplateDao.createTable();
            var applicationDao = session.getMapper(ApplicationDao.class);
            applicationDao.createTable();
            var applicationProgressDao = session.getMapper(ApplicationProgressDao.class);
            applicationProgressDao.createTable();
            var approverDao = session.getMapper(ApproverDao.class);
            approverDao.createTable();
            var tableQuestionDao = session.getMapper(TableQuestionDao.class);
            tableQuestionDao.createTable();
            var tableChoiceDao = session.getMapper(TableChoiceDao.class);
            tableChoiceDao.createTable();
            var tableAnswerDao = session.getMapper(TableAnswerDao.class);
            tableAnswerDao.createTable();
            var resourceDao = session.getMapper(ResourceDao.class);
            resourceDao.createTable();
        }

        // 检查是否有默认管理员账号
        var admin = UserService.getInstance().getUserByRole(Role.ADMIN);
        if (admin.size() == 0) {
            UserService.getInstance().createUser(
                    "admin", "默认管理员", "123456", "", Role.ADMIN
            );
        }
        System.out.println(System.getProperty("user.dir"));
    }

}
